package com.xuecheng.search.listener;

import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.search.service.SearchService;
import com.xuecheng.web.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class CoursePubListener {
    @Autowired
    private SearchService searchService;
    //监听课程发布
    //创建交换机和队列完成绑定
    @RabbitListener(bindings = @QueueBinding(//绑定
            value = @Queue("content.queue"),//创建队列
            exchange = @Exchange(value = "content-exchange",type = ExchangeTypes.TOPIC),
            //创建交换机
            key = "course.pub"//routingkey
    ))

    public void listenCoursePubId(Long coursePubId){
        System.out.println("课程发布id:"+coursePubId);
        // 数据同步
        try {
            searchService.MysqlToES(coursePubId);
        } catch (Exception e) {
            log.info("课程发布id：{}", coursePubId);
            throw new BusinessException(ErrorCode.COURSEPUBSHRRROR);  // 后期使用补偿机制 定时任务
        }
    }
    //创建交换机和队列完成绑定
    @RabbitListener(bindings = @QueueBinding(//绑定
            value = @Queue("content.delete"),//创建队列
            exchange = @Exchange(value = "content-exchange",type = ExchangeTypes.TOPIC),
            //创建交换机
            key = "delete"//routingkey
    ))
    public void deleteCoursePubId(Long coursePubId){
        System.out.println("课程发布id:"+coursePubId);
        // 删除数据
        try {
            searchService.deleteES(coursePubId);
        } catch (Exception e) {
            log.info("课程发布id：{}", coursePubId);
            throw new BusinessException(ErrorCode.COURSEPUBSHRRROR);  // 后期使用补偿机制 定时任务
        }
    }
}
